import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {AuthService} from "../service/auth/auth.service";

@Directive({
  selector: '[hasRole]'
})
export class HasRoleDirective {

  private hasView = false;

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private authService: AuthService) { }

  @Input()
  set hasRole(role: string) {
    let condition = false;
    //转为大写
    role = role.toUpperCase();
    //判断是否以ROLE_开头
    if(!role.startsWith("ROLE_")){
      role = "ROLE_" + role;
    }
    //判断权限和是否是超管
    let userRoles = this.authService.authInfo.roles;
    for(let i = 0; i < userRoles.length; i ++){
      if(userRoles[i].enname == role || userRoles[i].enname == "ROLE_SUPER_MANAGER"){
        condition = true;
        break;
      }
    }

    if (condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (!condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }

}
